package com.yxq.mdt.app.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.InflateException;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.ibase.IBaseActivity;
import com.yxq.mdt.app.base.ibase.IBaseContract;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.utils.PermissionUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * ================================================
 *
 * @function BaseActivity
 * Created by yd on 2019/02/15.
 * te
 * ================================================
 */
public abstract class BaseActivity<P extends IBaseContract.IBasePresenter> extends AppCompatActivity implements IBaseActivity {
    protected final String TAG = this.getClass().getSimpleName();
    private int statusBarColor = R.color.white;
    private boolean statusBarDarkFont = false;
    private boolean enableImmersion = false;
    private Unbinder mUnBinder;
    public ImmersionBar mImmersionBar;
    protected CommonTitleBar mCommonTitleBar;
    protected int page = 1;
    @Nullable
    protected P mPresenter;
    protected Activity mActivity;
    private InputMethodManager mInputMethodManager = null;

    private CostumerDialog mLoadingDialog;
    private boolean isFullScreen;
    private boolean isLayoutInDisplayCutoutModeShortEdges;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            int layoutResID = getLayoutId();
            // 如果initView返回0,框架则不会调用setContentView(),当然也不会 Bind ButterKnife
            if (layoutResID != 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    WebView.enableSlowWholeDocumentDraw();
                }
                setContentView(layoutResID);
                if (isFullScreen()) {
                    //全屏显示
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        if (isLayoutInDisplayCutoutModeShortEdges()) {
                            //兼容Android P 之后的水滴屏全屏显示
                            WindowManager.LayoutParams lp = getWindow().getAttributes();
                            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                            getWindow().setAttributes(lp);
                        }
                    }
                }

                // 绑定到butterknife
                mUnBinder = ButterKnife.bind(this);
                mActivity = this;
                mCommonTitleBar = findViewById(R.id.titlebar);
                if (null != mCommonTitleBar) {
                    mCommonTitleBar.setListener((v, action, extra) -> {
                        if (action == CommonTitleBar.ACTION_LEFT_BUTTON) {
                            back();
                        }
                    });
                }

            }
        } catch (Exception e) {
            if (e instanceof InflateException) {
                throw e;
            }
            e.printStackTrace();
        }
        mImmersionBar = ImmersionBar.with(this);
        if (!isFullScreen()) {
            //全屏情况禁用沉浸式代码
            initImmersionBar();
        }
        initView();
        initData(savedInstanceState);
    }

    /**
     * 顶部标题栏点击返回按钮事件
     */
    protected void back() {
        finish();
    }

    /**
     * 设置状态栏颜色 默认值colorAccent
     *
     * @param statusBarColor
     */
    public void setStatusBarColor(int statusBarColor) {
        this.statusBarColor = statusBarColor;
    }

    /**
     * 设置状态栏字体深色或亮色
     *
     * @param statusBarDarkFont true 深色
     */
    public void setStatusBarDarkFont(boolean statusBarDarkFont) {
        this.statusBarDarkFont = statusBarDarkFont;
    }

    public void setEnableImmersion(boolean enableImmersion) {
        this.enableImmersion = enableImmersion;
    }

    /**
     * Toast显示在底部
     *
     * @param msg
     */
    protected void showBottomToast(String msg) {
        ToastUtils.showShort(msg);
    }


    /**
     * Toast显示在正中间
     *
     * @param msg
     */
    protected void showCenterToast(String msg) {
        ToastUtils.showShort(msg);
    }

    protected void showCenterToast(int msg) {
        ToastUtils.showShort(msg);
    }


    @Override
    @SuppressLint("MissingSuperCall")
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        //super.onSaveInstanceState(outState);   //将这一行注释掉，阻止activity保存fragment的状态
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnBinder != null && mUnBinder != Unbinder.EMPTY) {
            mUnBinder.unbind();
            mUnBinder = null;
        }
        if (mPresenter != null) {
            mPresenter = null;
        }

        if (mLoadingDialog != null) {
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            mLoadingDialog = null;
        }
    }

    protected boolean isStrangePhone() {
        boolean strangePhone = "mx5".equalsIgnoreCase(Build.DEVICE)
                || "Redmi Note2".equalsIgnoreCase(Build.DEVICE)
                || "Z00A_1".equalsIgnoreCase(Build.DEVICE)
                || "hwH60-L02".equalsIgnoreCase(Build.DEVICE)
                || "hermes".equalsIgnoreCase(Build.DEVICE)
                || ("V4".equalsIgnoreCase(Build.DEVICE) && "Meitu".equalsIgnoreCase(Build.MANUFACTURER))
                || ("m1metal".equalsIgnoreCase(Build.DEVICE) && "Meizu".equalsIgnoreCase(Build.MANUFACTURER));


        return strangePhone;
    }

    public void initImmersionBar() {
        if (!isImmersionBarEnabled()) {
            return;
        }
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mImmersionBar.reset()
                    .fitsSystemWindows(true)
                    .statusBarColor(statusBarColor)
                    .statusBarDarkFont(statusBarDarkFont)
                    .init();
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mImmersionBar.reset()
                    .fullScreen(true)
                    .init();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
    }

    @Override
    public void onBackPressed() {
        if (isDialogShowing()) {
            hideLoadingDialog();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    public Boolean isImmersionBarEnabled() {
        return enableImmersion;
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.mInputMethodManager == null) {
            this.mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        if (localView != null && this.mInputMethodManager != null) {
            this.mInputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }


    /**
     * 显示对话框
     */
    public void showPermissionDialog(String contentText) {

        CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_confirm_cancel_layout)
                .setCancelable(true)
                .create();

        TextView title = dialog.findViewById(R.id.tv_title);

        title.setText("授权提示");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText(contentText);

        //继续
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("去授权");
        sure.setOnClickListener(v -> {
            dialog.dismiss();
            gotoPermissionManager();
        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

        dialog.show();
    }


    private static final int REQUEST_CODE_FOR_PERMISSION = 30001;

    public void gotoPermissionManager() {
        String brand = Build.BRAND;// 手机厂商
        if (TextUtils.equals(brand.toLowerCase(), "redmi") || TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
            PermissionUtils.gotoMiuiPermission(this, REQUEST_CODE_FOR_PERMISSION);// 小米
        } else if (TextUtils.equals(brand.toLowerCase(), "meizu")) {
            PermissionUtils.gotoMeizuPermission(this, REQUEST_CODE_FOR_PERMISSION);
        } else if (TextUtils.equals(brand.toLowerCase(), "huawei") || TextUtils.equals(brand.toLowerCase(), "honor")) {
            PermissionUtils.gotoHuaweiPermission(this, REQUEST_CODE_FOR_PERMISSION);
        } else {
            startActivityForResult(PermissionUtils.getAppDetailSettingIntent(this), REQUEST_CODE_FOR_PERMISSION);
        }
    }


    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_common_loading_layout)
                    .setCancelable(true)
                    .create();
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public void showLoadingDialog(boolean cancelable) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_common_loading_layout)
                    .setCancelable(true)
                    .setOutTouchCancelable(cancelable)
                    .setCancelable(cancelable)
                    .create();
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public void showLoadingDialog(String context) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_common_loading_layout)
                    .setText(R.id.tv_content, context)
                    .setCancelable(true)
                    .setOutTouchCancelable(false)
                    .create();
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public boolean isDialogShowing() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            return true;
        } else {
            return false;
        }
    }

    public void hideLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    public void setLayoutInDisplayCutoutModeShortEdges(boolean layoutInDisplayCutoutModeShortEdges) {
        isLayoutInDisplayCutoutModeShortEdges = layoutInDisplayCutoutModeShortEdges;
    }

    public boolean isLayoutInDisplayCutoutModeShortEdges() {
        return isLayoutInDisplayCutoutModeShortEdges;
    }

    public void setFullScreen(boolean fullScreen) {
        isFullScreen = fullScreen;
    }

    public boolean isFullScreen() {
        return isFullScreen;
    }

    public String getParentId() {
        return !TextUtils.isEmpty(Constant.getLoginUser().getBinding()) ? Constant.getLoginUser().getBinding() : "0";
    }
}

